package com.tim.app.ui.activity.record;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.application.library.log.DLOG;
import com.application.library.net.StringResponseCallback;
import com.application.library.widget.RatioImageView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.manager.ImagePickerManager;
import com.tim.app.server.api.API_App;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.entry.Story;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.StoryDetailResult;
import com.tim.app.server.result.UploadResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.StoryDetailActivity;
import com.tim.app.ui.dialog.TipDialog;
import com.tim.app.ui.widget.imagepick.bean.ImageItem;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;

import java.io.File;
import java.util.ArrayList;

import jp.wasabeef.glide.transformations.BlurTransformation;

/**
 * 录音发布
 */
public class PublishRecordActivity extends BaseActivity {

    private static final String TAG = "PublishRecordActivity";

    private TextView tvGiveUp;
    private TextView tvPublish;

    private String audioUrl = "";
    private String totalTime;
    private String albumId;

    private View rlAddImage;
    private RatioImageView rivStoryImage;
    private RatioImageView rivStoryHeaderBg;

    private EditText etContent;

    private String path;
    ImagePickerManager imagePicker;

    private TextView tvCurrentInputCount;

    /**
     * 启动录音编辑页面
     *
     * @param context
     */
    public static void start(Context context, String recordUrl, String time, String albumId) {
        Intent intent = new Intent(context, PublishRecordActivity.class);
        intent.putExtra("url", recordUrl);
        intent.putExtra("time", time);
        intent.putExtra("albumId", albumId);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_publish_record;
    }

    @Override
    public void initView() {
        tvGiveUp = (TextView) findViewById(R.id.tvGiveUp);
        tvPublish = (TextView) findViewById(R.id.tvPublish);
        rlAddImage = findViewById(R.id.rlAddImage);

        rivStoryImage = (RatioImageView) findViewById(R.id.rivStoryImage);
        rivStoryHeaderBg = (RatioImageView) findViewById(R.id.rivStoryHeaderBg);

        etContent = (EditText) findViewById(R.id.etContent);

        tvCurrentInputCount = (TextView) findViewById(R.id.tvCurrentInputCount);

        tvCurrentInputCount.setText(getString(R.string.storyTitleInputCount, "0"));
        tvGiveUp.setOnClickListener(this);
        tvPublish.setOnClickListener(this);
        rlAddImage.setOnClickListener(this);
        rivStoryImage.setOnClickListener(this);

        audioUrl = getIntent().getStringExtra("url");
        totalTime = getIntent().getStringExtra("time");
        albumId = getIntent().getStringExtra("albumId");

        imagePicker = ImagePickerManager.ins();
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(true);
        if (android.os.Build.MODEL.contains("HM NOTE")) {
            imagePicker.setShowCamera(false);
        }

        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String value = etContent.getText().toString().trim();
                if (value.length() > 20) {
                    etContent.setText(value.substring(0, 20));
                    etContent.setSelection(etContent.getText().length());
                    ToastUtil.showToast("不能超过20个字");
                }
                if (!TextUtils.isEmpty(etContent.getText().toString()) && !TextUtils.isEmpty(path)) {
                    tvPublish.setEnabled(true);
                } else {
                    tvPublish.setEnabled(false);
                }
                tvCurrentInputCount.setText(getString(R.string.storyTitleInputCount, String.valueOf(etContent.getText().toString().length())));
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvGiveUp:
                showExitDialog();
                break;
            case R.id.tvPublish:
                String title = etContent.getText().toString();
                ;
                if (TextUtils.isEmpty(title)) {
                    ToastUtil.showToast("故事标题不能为空！");
                    return;
                }
                if (TextUtils.isEmpty(path)) {
                    ToastUtil.showToast("故事封面不能为空！");
                    return;
                }
                uploadStoryImage(path, title, albumId);
                break;
            case R.id.rivStoryImage:
            case R.id.rlAddImage:
                imagePicker.gallerySelectedPic(this);
                break;
        }
    }

    /**
     * 上传故事封面
     *
     * @param path
     * @param title
     */
    private void uploadStoryImage(final String path, final String title, final String albumId) {
        showLoadingDialog();
        API_App.ins().uploadData(TAG, path, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK) {
                    UploadResult result = new Gson().fromJson(resultValue, UploadResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                        String url = result.getRes().getHashmap().getImgurl();
                        publishStory(title, "", url, audioUrl, totalTime, albumId);
                    }
                } else {
                    hideLoadingDialog();
                    DLOG.e(TAG, errMsg);
                }
                return false;
            }
        });
    }

    /**
     * 发布故事
     *
     * @param title
     * @param content
     * @param image
     * @param audioUrl
     * @param time
     */
    private void publishStory(String title, String content, String image, String audioUrl, String time, String albumId) {
        API_Found.ins().publishStory(TAG, title, content, image, audioUrl, time, albumId, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK) {
                    hideLoadingDialog();
                    StoryDetailResult result = new Gson().fromJson(resultValue, StoryDetailResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getStory()) {
                        Story story = result.getRes().getStory();
                        ArrayList<Story> list = new ArrayList<Story>();
                        list.add(story);
                        StoryDetailActivity.start(PublishRecordActivity.this, list, 0, false);
                        finish();
                    }
                } else {
                    hideLoadingDialog();
                    DLOG.e(TAG, errMsg);
                }
                return false;
            }
        });
    }

    private void showExitDialog() {
        TipDialog dialog = new TipDialog(this);
        dialog.setTextDes(getString(R.string.cancel_exit_dialog_content));
        dialog.setButton1(getString(R.string.action_ok), new TipDialog.DialogButtonOnClickListener() {
            @Override
            public void onClick(View button, TipDialog dialog) {
                dialog.dismiss();
                finish();
            }
        });
        dialog.setButton2(getString(R.string.action_cancel), new TipDialog.DialogButtonOnClickListener() {
            @Override
            public void onClick(View button, TipDialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ImagePickerManager.RESULT_CODE_ITEMS) {
            if (data == null) {
                return;
            }
            if (requestCode == ImagePickerManager.RESULT_CODE_GALLERY) {//从图库返回
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePickerManager.EXTRA_RESULT_ITEMS);
                for (int i = 0; i < images.size(); i++) {
                    ImageItem item = images.get(i);
                    path = item.path;
                    rlAddImage.setVisibility(View.GONE);
                    rivStoryImage.setVisibility(View.VISIBLE);
                    rivStoryHeaderBg.setVisibility(View.VISIBLE);
                    BitmapLoader.ins().loadLocalImage(path, rivStoryImage);
                    Glide.with(PublishRecordActivity.this)
                            .load(new File(path))
                            .bitmapTransform(new BlurTransformation(this, AppKey.DETIAL_RADIUS))//高斯模糊
                            .into(rivStoryHeaderBg);
                    if (!TextUtils.isEmpty(etContent.getText().toString()) && !TextUtils.isEmpty(path)) {
                        tvPublish.setEnabled(true);
                    } else {
                        tvPublish.setEnabled(false);
                    }
                }
            }
        } else if (requestCode == ImagePickerManager.REQUEST_CODE_TAKE) {
            //发送广播通知图片增加了
            ImagePickerManager.galleryAddPic(this, imagePicker.getTakeImageFile());
            path = imagePicker.getTakeImageFile().getAbsolutePath();
            rlAddImage.setVisibility(View.GONE);
            rivStoryImage.setVisibility(View.VISIBLE);
            rivStoryHeaderBg.setVisibility(View.VISIBLE);
            BitmapLoader.ins().loadLocalImage(path, rivStoryImage);
            Glide.with(PublishRecordActivity.this)
                    .load(new File(path))
                    .bitmapTransform(new BlurTransformation(this, AppKey.DETIAL_RADIUS))//高斯模糊
                    .into(rivStoryHeaderBg);
            if (!TextUtils.isEmpty(etContent.getText().toString()) && !TextUtils.isEmpty(path)) {
                tvPublish.setEnabled(true);
            } else {
                tvPublish.setEnabled(false);
            }
        }
    }

    @Override
    public void onBackPressed() {
        showExitDialog();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

}
